from datetime import datetime

from config.database import AsyncSessionLocal
from config.get_redis import RedisUtil
from module_admin.service.config_service import ConfigService


def job(*args, **kwargs):
    """
    定时任务执行同步函数示例
    """
    print(args)
    print(kwargs)
    print(f'{datetime.now()}同步函数执行了')


async def async_job(*args, **kwargs):
    """
    定时任务执行异步函数示例
    """
    print(args)
    print(kwargs)
    print(f'{datetime.now()}异步函数执行了')


async def refresh_cache_job(*args, **kwargs):
    """
    定时任务：定期刷新缓存
    """
    try:
        # 使用 AsyncSessionLocal 创建异步会话
        async with AsyncSessionLocal() as session:
            # 从 app.state 获取 redis 连接（需确保上下文可用）
            redis = await RedisUtil.create_redis_pool()

            # 调用服务方法，传入 session 和模拟 request
            await ConfigService.refresh_sys_config_services(
                request=None,  # 模拟 request，实际通过 app.state 访问
                query_db=session
            )

        print(f"{datetime.now()} 缓存刷新成功")
    except Exception as e:
        print(f"{datetime.now()} 缓存刷新失败: {e}")
